/* eslint-disable no-debugger */
/* eslint-disable no-unsafe-optional-chaining */
/* eslint-disable react/prop-types */
/* eslint-disable react/display-name */
import {
	DeleteOutlined,
	EditOutlined,
	ExclamationCircleFilled,
	ExportOutlined,
	ImportOutlined,
	PlusOutlined,
	SyncOutlined,
	UserOutlined
} from "@ant-design/icons";
import { Button, Card, Dropdown, Flex, Input, List, MenuProps, Modal, Space, Typography, Upload, message, theme } from "antd";
import React, { useEffect, useRef, useState } from "react";
import { useEmotionCss } from "@ant-design/use-emotion-css";
import { DictValueEnum } from "@/components/DictTag";
import { getDictType, getPageList as getList, remove, save, update } from "@/services/api/module/tenant/developer/dictType";
import {
	EditableProTable,
	ModalForm,
	ProColumns,
	ProForm,
	ProFormInstance,
	ProFormRadio,
	ProFormText,
	ProFormTextArea,
	ProFormUploadDragger,
	StepsForm
} from "@ant-design/pro-components";
const { useToken } = theme;
import ScrollBar from "@/components/ProSelectIcon/components/ScrollBar";
import { syncDict } from "@/services/api/module/tenant/developer/dict";
import { dict } from "@/utils/DictionaryCacheManager";
import download from "@/utils/download";
const { Search } = Input;
import UploadIcon from "@/assets/uploadIcon.svg";
import IconFont from "@/components/IconFont";
export type DictTypeParams = Record<string, unknown> & Partial<API.System.DictType>;
export type DictTypeFormProps = {
	handleCancel: () => void;
	onSubmit: (values: DictTypeParams) => Promise<any>;
	open: boolean;
	dictCategory: DictValueEnum | any;
	id?: number | undefined | string;
};
//字典类型表单
const DictTypeForm: React.FC<DictTypeFormProps> = ({ id, open, handleCancel, dictCategory, onSubmit }) => {
	const formRef = useRef<ProFormInstance>();
	// 提交表单
	const handleFinish = async (values: DictTypeParams) => {
		return onSubmit({ ...values, id: id ? id : undefined });
	};
	useEffect(() => {
		if (id) {
			setFormValue(id);
		}
	}, [id]);
	// 表单赋值
	const setFormValue = (id: number | string | undefined) => {
		getDictType(id).then(data => {
			formRef?.current?.setFieldsValue(data);
		});
	};
	return (
		<ModalForm<DictTypeParams>
			width={500}
			formRef={formRef}
			title={id ? "修改字典类型" : "创建字典类型"}
			grid={true}
			open={open}
			modalProps={{
				destroyOnClose: true,
				onCancel: () => {
					handleCancel();
				}
			}}
			onFinish={handleFinish}
		>
			<ProFormRadio.Group
				radioType="button"
				label="配置类型"
				name="category"
				rules={[
					{
						required: true,
						message: "请输入字典类型名称"
					}
				]}
				initialValue="0"
				valueEnum={dictCategory}
			/>
			<ProFormText
				name="dictName"
				rules={[
					{
						required: true,
						message: "请输入字典类型名称"
					}
				]}
				placeholder="请输入字典类型"
				label="字典名称"
			/>
			<ProFormText
				name="dictType"
				label="字典类型"
				rules={[
					{
						required: true,
						message: "请输入字典类型"
					}
				]}
				placeholder="请输入字典类型"
			/>
			<ProFormTextArea placeholder={"请输入备注"} label="备注" />
		</ModalForm>
	);
};
// 列表项
const ListItem: React.FC<any> = React.forwardRef(
	({ id, onSelect, showActions, position, item, onEditor, onRemove, selectIndex }, ref) => {
		const { token } = useToken();
		const dictTypeClassName = useEmotionCss(({ token }) => {
			return {
				width: "100%",
				height: "40px",
				padding: "0 10px",
				// overflow: "hidden",
				borderRadius: token.borderRadiusSM,
				"&:hover": {
					background: token.colorBgTextHover,
					cursor: "pointer"
				}
			};
		});
		return (
			<List.Item
				onClick={() => {
					onSelect(id);
				}}
				key={id}
				style={{ width: "100%", padding: "0", background: id == selectIndex ? token.colorBgTextHover : "" }}
			>
				<Flex
					onMouseEnter={() => showActions(id)}
					onMouseLeave={() => showActions(null)}
					justify="space-between"
					align="center"
					className={dictTypeClassName}
				>
					<div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
						<Typography.Text ellipsis>{item?.dictName}</Typography.Text>
					</div>
					{position === id ? (
						<div className={"oper"}>
							<Space size={10}>
								<Typography.Link
									onClick={e => {
										e.stopPropagation();
										onEditor(item?.id);
									}}
								>
									<EditOutlined />
								</Typography.Link>
								<Typography.Link
									type="danger"
									onClick={e => {
										e.stopPropagation();
										onRemove(item?.dictName, item?.id);
									}}
								>
									<DeleteOutlined />
								</Typography.Link>
							</Space>
						</div>
					) : (
						<Typography.Text ellipsis type="secondary">
							{item?.dictType}
						</Typography.Text>
					)}
				</Flex>
			</List.Item>
		);
	}
);

const ImportModal: React.FC<{ category: DictValueEnum }> = ({ category }) => {
	const [dataSource, setDataSource] = useState<readonly API.System.DictType[]>();
	const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
	const columns: ProColumns<API.System.DictType>[] = [
		{
			title: "字典分类",
			dataIndex: "category",
			valueType: "text",
			valueEnum: category
		},
		{
			title: "字典名称",
			dataIndex: "dictName",
			valueType: "text",
			ellipsis: true
		},
		{
			title: "字典编码",
			dataIndex: "dictType",
			valueType: "text"
		},
		{
			title: "描述",
			dataIndex: "remark",
			valueType: "text"
		}
	];
	const readJsonFIle = (file: any) => {
		const reader = new FileReader();
		reader.onload = function (e: any) {
			try {
				const jsonData = JSON.parse(e?.target?.result);
				// console.log(jsonData);
				setEditTableData(jsonData);
			} catch (error) {
				console.log(error);
			}
		};
		reader.readAsText(file);
	};
	const setEditTableData = (jsonData: any) => {
		setDataSource(jsonData);
	};
	return (
		<StepsForm<{
			name: string;
		}>
			// formRef={formRef}
			// onFinish={async () => {
			// 	await waitTime(1000);
			// 	message.success("提交成功");
			// }}
			formProps={{
				validateMessages: {
					required: "此项为必填项"
				}
			}}
			stepsFormRender={(dom, submitter) => {
				return (
					<Modal title="导入字典" width={900} open={true} footer={submitter} destroyOnClose>
						{dom}
					</Modal>
				);
			}}
		>
			<StepsForm.StepForm<{
				file: any;
			}>
				style={{
					width: 600
				}}
				stepProps={{
					icon: <IconFont type="icon-shujuzidianzhudang" />
				}}
				onFinish={(values: any) => {
					console.log("value", values?.file[0].originFileObj);
					readJsonFIle(values?.file[0].originFileObj);
					return Promise.resolve(true);
				}}
				name="base"
				title="上传字典"
			>
				<ProFormUploadDragger
					max={1}
					icon={<img src={UploadIcon} width={80} />}
					title="上传字典"
					name="file"
					accept=".json"
					description="点击上传JSON文件"
					fieldProps={{
						listType: "picture",
						multiple: true,
						maxCount: 1,
						beforeUpload: (file, fileList) => {
							if (fileList.length > 1) {
								return Upload.LIST_IGNORE;
							}
							return false;
						}
					}}
					style={{ width: "600px" }}
				/>
				<div>
					导入的模板下载：<Typography.Link>点击下载</Typography.Link>
				</div>
			</StepsForm.StepForm>
			<StepsForm.StepForm<{
				checkbox: string;
			}>
				stepProps={{
					icon: <IconFont type="icon-shujujiexi" />
				}}
				name="checkbox"
				title="字典解析"
				onFinish={async () => {
					// console.log(formRef.current?.getFieldsValue());
					return true;
				}}
			>
				<EditableProTable<API.System.DictType>
					ghost
					pagination={{
						pageSize: 10
					}}
					columns={columns}
					rowKey="id"
					// toolBarRender={() => {
					// 	return [
					// 		<Button
					// 			type="primary"
					// 			key="save"
					// 			onClick={() => {
					// 				// dataSource 就是当前数据，可以调用 api 将其保存
					// 			}}
					// 		>
					// 			保存数据
					// 		</Button>
					// 	];
					// }}
					recordCreatorProps={false}
					value={dataSource}
					editable={{
						type: "multiple",
						editableKeys,
						actionRender: (row, config, defaultDoms) => {
							return [defaultDoms.delete];
						},
						onValuesChange: (record, recordList) => {}
					}}
				/>
			</StepsForm.StepForm>
		</StepsForm>
	);
};
const DictTypeList: React.FC<{ onSelect: (data: any) => void }> = ({ onSelect = () => {} }) => {
	const [dictTypeData, setDictTypeData] = useState<any>([]);
	const [selectIndex, setSelectIndex] = useState<any>();
	const [currentId, setCurrentId] = useState<any>(undefined);
	const [formOpen, setFormOpen] = useState<any>();
	const [loading, setLoading] = useState(false);
	const [search, SetSearh] = useState("");
	const [messageApi, contextHolder] = message.useMessage();
	const [position, setPosition] = useState<any>();
	const [dictCategory, setDictCapteGory] = useState<any>();
	//初始化请求
	useEffect(() => {
		getDictTypeList();
	}, []);
	// 初始化字典
	useEffect(() => {
		dict.getDict("sys_category_type").then(data => {
			setDictCapteGory(data);
		});
	}, []);
	//请求字典类型
	const getDictTypeList = () => {
		setLoading(true);
		getList().then(data => {
			setDictTypeData(data);
			setLoading(false);
		});
	};
	//删除
	const handleRemove = (name: string, id: number) => {
		Modal.confirm({
			title: "删除警告",
			icon: <ExclamationCircleFilled />,
			content: (
				<div>
					您确定要删除字典类型名为: “ <Typography.Text strong>{name}</Typography.Text> ” 吗？
					<br /> 执行此操作后，相关数据将被永久删除，无法恢复。
				</div>
			),
			okText: "确认",
			cancelText: "取消",
			onOk() {
				return new Promise((reslove, reject) => {
					remove(id)
						.then((res: any) => {
							message.success(res.msg);
							reflshList();
							reslove(true);
						})
						.catch(() => {
							reject(true);
						});
				});
			},
			onCancel() {}
		});
	};
	//导出
	const exportJSon = () => {
		download.export("system/dict/type/export", "");
	};
	//下拉菜单项
	const items: MenuProps["items"] = [
		{
			key: "add",
			label: "新增"
		},
		{
			key: "async",
			label: "刷新缓存"
		},
		{
			key: "export",
			label: "导出"
		},
		{
			key: "import",
			label: "导入"
		}
	];
	const handleMenuClick: MenuProps["onClick"] = e => {
		if (e.key === "async") {
			handleAsync();
		} else if (e.key === "add") {
			setFormOpen(true);
		} else if (e.key === "export") {
			exportJSon();
		}
	};
	// 刷新缓存
	const handleAsync = () => {
		messageApi.open({
			type: "loading",
			content: "正在刷新",
			duration: 0
		});
		return new Promise((reslove, reject) => {
			syncDict()
				.then(res => {
					messageApi.destroy();
					reslove(res);
					message.success(res.msg);
				})
				.catch(() => {
					messageApi.destroy();
					reject("");
				});
		});
	};
	// 保存
	const handleSave = async (values: DictTypeParams) => {
		return new Promise((resolve, reject) => {
			save({ ...values } as DictTypeParams)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 修改
	const handleUpdate = async (values: DictTypeParams) => {
		return new Promise((resolve, reject) => {
			update({ ...values } as DictTypeParams)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	//刷新列表
	const reflshList = () => {
		setDictTypeData([]);
		getDictTypeList();
	};
	// 关闭表单刷新列表
	const handleTableForm = async () => {
		reflshList();
		handleCloseForm();
	};
	//表单
	const handleCloseForm = () => {
		setFormOpen(false);
		setCurrentId(undefined);
	};
	//表单打开
	const handleFormOpen = (id: number) => {
		setCurrentId(id);
		setFormOpen(true);
	};

	return (
		<>
			{contextHolder}
			<Card
				styles={{
					header: {
						padding: "0 15px"
					},
					body: {
						padding: "5px 10px"
					}
				}}
				bordered
				title="字典类型"
				extra={
					<Dropdown menu={{ items, onClick: handleMenuClick }} placement="bottom">
						<Button type="primary" ghost>
							操作字典类型
						</Button>
					</Dropdown>
				}
				style={{ height: "calc(100vh - 100px)" }}
			>
				<Search placeholder="输入关键字搜索" onSearch={v => {}} allowClear style={{ marginBottom: 5, marginTop: 5 }} />
				<Dropdown
					menu={{
						items,
						onClick: handleMenuClick
					}}
					trigger={["contextMenu"]}
				>
					<ScrollBar mode="hover" maxHeight={"calc(100vh - 220px)"}>
						<List<API.System.DictType>
							loading={loading}
							style={{ height: "calc(100vh - 90px)", marginTop: "4px" }}
							split={false}
							dataSource={dictTypeData}
							header={null}
							renderItem={(item, index) => (
								<ListItem
									key={index}
									index={index}
									selectIndex={selectIndex}
									id={item?.id}
									item={item}
									showActions={(v: any) => {
										setPosition(v);
									}}
									position={position}
									onSelect={(id: number) => {
										if (selectIndex === item?.id) {
											setSelectIndex(undefined);
											onSelect(undefined);
											return;
										}
										setSelectIndex(id);
										onSelect(item);
									}}
									onEditor={(id: number) => {
										handleFormOpen(id);
									}}
									onRemove={(name: string, id: number) => {
										handleRemove(name, item?.id);
									}}
								/>
							)}
						/>
					</ScrollBar>
				</Dropdown>
				<DictTypeForm
					id={currentId}
					dictCategory={dictCategory}
					open={formOpen}
					handleCancel={handleCloseForm}
					onSubmit={async (values: DictTypeParams) => {
						return values.id ? await handleUpdate(values) : await handleSave(values);
					}}
				/>
				<ImportModal category={dictCategory} />
			</Card>
		</>
	);
};

export default DictTypeList;
